package 腐烂的苹果;

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param grid int整型ArrayList<ArrayList<>>
     * @return int整型
     */
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public int rotApple(ArrayList<ArrayList<Integer>> grid) {
        int n = grid.size();
        int m = grid.get(0).size();
        Queue<PII> q = new LinkedList<>();
        boolean[][] st = new boolean[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid.get(i).get(j) == 2) {
                    q.offer(new PII(i, j));
                    st[i][j] = true;
                }
            }
        }
        int res = 0;
        while (!q.isEmpty()) {
            int size = q.size();
            while (size-- > 0) {
                PII t = q.poll();
                for (int i = 0; i < 4; i++) {
                    int a = t.x + dx[i];
                    int b = t.y + dy[i];
                    if (a < 0 || a >= n || b < 0 || b >= m) {
                        continue;
                    }
                    if (st[a][b]) {
                        continue;
                    }
                    if (grid.get(a).get(b) != 1) {
                        continue;
                    }
                    st[a][b] = true;
                    q.offer(new PII(a, b));
                }
            }
            res++;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid.get(i).get(j) == 1 && st[i][j] == false) {
                    return -1;
                }
            }
        }
        return res - 1;
    }
}

class PII {
    int x, y;

    public PII(int x, int y) {
        this.x = x;
        this.y = y;
    }
}